package com.atguigu.redis.single;

import io.reactivex.Observable;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

public class JiaotiDemo {
    public  static ReentrantLock reentrantLock = new ReentrantLock();
    public static Condition condition = reentrantLock.newCondition();
    public static CountDownLatch countDownLatch = new CountDownLatch(3);
    public static CyclicBarrier cyclicBarrier = new CyclicBarrier(3,()->{
        System.out.println("success");
    });
    public static volatile boolean FLAG =false;

    public static void main(String[] args) {
    char [] ab ="123456".toCharArray();
    char[]ac = "ABCDEFG".toCharArray();


        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();

        }
        new Thread(()->{
            for (int i = 0; i < ab.length; i++) {
                try {
                reentrantLock.lock();
                countDownLatch.countDown();
                    while (FLAG){
                        condition.await();
                    }
                    System.out.println(ab[i]);
                    FLAG =true;
                    condition.signalAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    reentrantLock.unlock();
                }
            }
        }).start();

        new Thread(()->{
            for (int i = 0; i < ac.length; i++) {
                reentrantLock.lock();
                try {
                    while (!FLAG){
                        condition.await();
                    }
                    System.out.println(ac[i]);
                    FLAG =false;
                    condition.signalAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    reentrantLock.unlock();
                }
            }
        }).start();
    }
}
